package com.jinlejia.erp.ui.mine.pushmoney;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ListPushMoneyAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityListPushMoneyBinding;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 提成明细
 */
public class ListPushMoneyActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {


    private String headers[] = {"成交类型", "提成类型", "月份"};
    private String cjType[] = {"不限", "二手房", "一手房", "租赁", "垫资"};
    private String tcType[] = {"不限", "个人提成", "带训提成", "培育带训经理提成", "培育城市合伙人提成",
            "培育城市副总经理提成", "培育城市总经理提成", "培育分成人提成"};
    private List<View> popupViews = new ArrayList<>();
    private GirdDropDownAdapter cjTypeAdapter;
    private GirdDropDownAdapter tcTypeAdapter;
    private ListPushMoneyAdapter adapter;
    private String tradeType = "";
    private String commissionType = "";
    private String month = "";

    private ActivityListPushMoneyBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_list_push_money);

        binding.backBtn.setOnClickListener(view -> finish());
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        //init type menu
        final ListView cjTypeView = new ListView(this);
        cjTypeAdapter = new GirdDropDownAdapter(this, Arrays.asList(cjType));
        cjTypeView.setAdapter(cjTypeAdapter);
        cjTypeView.setOnItemClickListener((parent, view, position, id) -> {
            binding.dropDownMenu.setTabText(position == 0 ? headers[0] : cjType[position]);
            binding.dropDownMenu.closeMenu();
            switch (position) {
                case 0:
                    tradeType = "";
                    break;
                case 1:
                    tradeType = "ershoufang";
                    break;
                case 2:
                    tradeType = "xinfang";
                    break;
                case 3:
                    tradeType = "zulin";
                    break;
                case 4:
                    tradeType = "jinrong";
                    break;
                default:
                    tradeType = "";
            }
            getData();
        });

        final ListView tcTypeView = new ListView(this);
        tcTypeAdapter = new GirdDropDownAdapter(this, Arrays.asList(tcType));
        tcTypeView.setAdapter(tcTypeAdapter);
        tcTypeView.setOnItemClickListener((parent, view, position, id) -> {
            binding.dropDownMenu.setTabText(position == 0 ? headers[1] : tcType[position]);
            binding.dropDownMenu.closeMenu();
            switch (position) {
                case 0:
                    commissionType = "";
                    break;
                case 1:
                    commissionType = "pin";
                    break;
                case 2:
                    commissionType = "trainingMangerPin";
                    break;
                case 3:
                    commissionType = "developTrainingManagerPin";
                    break;
                case 4:
                    commissionType = "developCityPartnerPin";
                    break;
                case 5:
                    commissionType = "developCityDeputyManagerPin";
                    break;
                case 6:
                    commissionType = "developCityManagerPin";
                    break;
                case 7:
                    commissionType = "developPin";
                    break;
                default:
                    commissionType = "";
            }
            getData();
        });

        View timeView = new View(this);

        //init popupViews
        popupViews.add(cjTypeView);
        popupViews.add(tcTypeView);
        popupViews.add(timeView);

        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);
        binding.dropDownMenu.setOnMenuChangeListener(menuID -> {
            if (menuID == 4) {
                TimePickerDialog visitFloorPicker = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH)
                        .setTitleStringId("")
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.yellow))
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.colorTip))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.colorAccent))
                        .setCallBack((timePickerView, millseconds) -> {
                            binding.dropDownMenu.setTabText(DateUtil.getTime(millseconds, "yyyy-MM"));
                            binding.dropDownMenu.closeMenu();
                            month = DateUtil.getTime(millseconds, "yyyy-MM").concat("-01");
                            getData();
                        })
                        .build();
                visitFloorPicker.show(getSupportFragmentManager(), "year_month");
            }
        });

        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setHasFixedSize(true);
        ArrayList<Map<String, Object>> data = new ArrayList<>();
        adapter = new ListPushMoneyAdapter(data);
        binding.recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((view, o) -> {
            Map<String, Object> map = (Map<String, Object>) o;
            Intent intent = new Intent(ListPushMoneyActivity.this, DetailPushMoneyActivity.class);
            intent.putExtra("commissionType", map.get("commissionType").toString());
            intent.putExtra("costId", map.get("costId").toString());
            startActivity(intent);
        });
        //默认加载当前月
        month = getIntent().getStringExtra("month").concat("-01");
        getData();

    }


    @Override
    public void onRefresh() {
        getData();
    }

    private void getData() {
        final JSONObject json = new JSONObject();
        json.put("tradeType", tradeType);
        json.put("creatTime", month);
        json.put("commissionType", commissionType);
        OkHttpUtils
                .postString()
                .url(ApiConfig.MY_COMMISSION_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(json.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        if (DataFilter.filter(ListPushMoneyActivity.this, response, adapter)) {
                            JSONObject jsonObject = JSON.parseObject(response.get("data").toString());
                            if (jsonObject.containsKey("commissionList")) {
                                ArrayList<Map<String, Object>> data = JSON.parseObject(jsonObject.getJSONArray("commissionList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                                adapter.setData(data);
                                adapter.removeAllHeader();
                                Map<String, Object> head = new HashMap<>();
                                head.put("createTime", jsonObject.get("createTime") != null ? jsonObject.get("createTime") : 0L);
                                head.put("commissionSum", jsonObject.get("commissionSum"));
                                adapter.addHeader(head);
                            } else {
                                adapter.changeMode(YfListMode.MODE_EMPTY);
                            }
                        }
                    }
                });
    }
}
